﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Xml.Linq;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using UCL;
using UCL.ADF;

namespace SoIM
{
    /// <summary>
    /// 通用进度条
    /// </summary>
    /// <remarks>2013-10-30 by sutroon</remarks>
    public partial class frmAsyncTask : Form
    {
        /// <summary>
        /// 处理完成后要继续处理的事件
        /// </summary>
        public Action CompletedHandler { get; set; }
        int counter { get; set; }
        public frmAsyncTask()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void frmAsyncTask_Load(object sender, EventArgs e)
        {
            Action act = this.LoadUser;
            IAsyncResult iar = act.BeginInvoke(null, null);
        }

        public void SetTipText(string s,params object[] args)
        {
            lblTip.Text = string.Format(s, args);
        }

        public void InitCounter(int count)
        {
            this.pbMain.Maximum = count;
            this.lblCount.Text = string.Format("{0}/{1}", this.counter, this.pbMain.Maximum);
        }

        /// <summary>
        /// 更新进度计数器
        /// </summary>
        public void UpdateCounter()
        {
            this.counter++;
            if (this.counter == this.pbMain.Maximum)
            {
                if (CompletedHandler != null) this.Invoke(CompletedHandler);
                this.Close();
                return;
            }
            this.lblCount.Text = string.Format("{0}/{1}", this.counter, this.pbMain.Maximum);
            this.pbMain.Value = this.counter;
            
        }

        /// <summary>
        /// 从服务器加载用户数据
        /// </summary>
        private void LoadUser()
        {
            this.SetTipText("正在从服务器读取数据...");
            // 读取数据
            string xml = WSDLHelper.InvokeMethod<string>("SelectTreeXml", new object[] { "xyx", "select ID, Name, '1' as IsGroup from tUserDepartment where ParentID='{0}' order by Ordinal", Guid.Empty.ToString(), "Select AgentID as ID, (Name+'('+Cast(AgentID as varchar)+')') as Name, Face, '0' as IsGroup, LoginIP from tUserMember where DepartmentID='{0}'", "Select ID, Name, ParentID, '1' as IsGroup from tUserDepartment where ID='{0}' order by Ordinal" });
            if (xml == null)
            {
                WSDLHelper.ShowMessage("LoadDepartmentAndUser");
                return;
            }
            ADFS.Instance.Site.SetFileText("UserDB.soxf", xml);

            DataTable dtFaces = WSDLHelper.InvokeMethod<DataTable>("SelectTable", new object[] { "xyx", "tUserMember", "Face <> ''", "Face" });
            if (dtFaces == null)
            {
                WSDLHelper.ShowMessage("LoadFace");
                return;
            }

            Action<DataTable> actLoadImages = LoadImages;
            IAsyncResult iar = actLoadImages.BeginInvoke(dtFaces, null, null);
        }



        /// <summary>
        /// 加载图片
        /// </summary>
        /// <param name="xml"></param>
        /// <remarks>2013-10-29 by sutroon</remarks>
        private void LoadImages(DataTable dt)
        {
            if (dt.Rows.Count == 0)
            {
                if (CompletedHandler != null) CompletedHandler();
                this.Close();
                return;
            }
            string facefolder =ADFS.Instance.Site.GetFolder("Faces").ToString()+"\\";
            if (!Directory.Exists(facefolder)) Directory.CreateDirectory(facefolder);
            string filename;
            Action<string> actDownloadImg = (string url) =>
            {
                filename = System.IO.Path.GetFileName(url);
                this.SetTipText("下载:{0}...", filename);
                System.Net.WebClient wc = new System.Net.WebClient();
                wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadFileCompleted);
                wc.DownloadFileAsync(new Uri(url), facefolder + filename);
            };

            this.InitCounter(dt.Rows.Count);
            foreach (DataRow r in dt.Rows)
            {
                actDownloadImg.Invoke(r[0].ToString());
            }
        } 

        private void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            this.UpdateCounter();
        }
    }
}
